package cn.deali.homework9.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.viewpager.widget.ViewPager;

import android.Manifest;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import cn.deali.homework9.MainApp;
import cn.deali.homework9.service.MusicService;
import cn.deali.homework9.R;
import cn.deali.homework9.adapter.MainViewPagerAdapter;
import cn.deali.homework9.model.LocalMusic;
import cn.deali.homework9.model.Music;
import cn.deali.homework9.utils.LocalMusicUtils;

public class MainActivity extends AppCompatActivity {
    //还没做：在线音乐的数据获取、下一首
    ViewPager viewPager;
    TextView localMusic;
    TextView onlineMusic;
    TextView textView_name;
    TextView textView_artist;
    ImageView imageView;

    ArrayList<TextView> textViewList;
    protected final int REQUEST_EXTERNAL_STORAGE = 10;
    ImageButton playBtn;
    MusicService.MusicBinder musicBinder;

    ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            musicBinder = (MusicService.MusicBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 去掉标题栏 要在 setContentView(R.layout.activity_main); 之前
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        // 状态栏沉浸
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().setStatusBarColor(getResources().getColor(android.R.color.holo_red_light));

        setContentView(R.layout.activity_main);

        textView_name = findViewById(R.id.name);
        textView_artist = findViewById(R.id.artist);
        imageView = findViewById(R.id.img);
        localMusic = findViewById(R.id.localMusic);
        onlineMusic = findViewById(R.id.onlineMusic);
        playBtn = findViewById(R.id.playBtn);
        //服务
        Intent intent = new Intent(MainActivity.this, MusicService.class);
        startService(intent);//开始服务，退出页面后仍然服务
        bindService(intent, connection, Service.BIND_AUTO_CREATE);

        //渲染view_pager
        viewPager = findViewById(R.id.view_pager);
        MainViewPagerAdapter adapter = new MainViewPagerAdapter(this, getSupportFragmentManager());
        viewPager.setAdapter(adapter);

        textViewList = new ArrayList<TextView>();
        textViewList.add(localMusic);
        textViewList.add(onlineMusic);
        textViewList.get(0).setTextColor(Color.WHITE);

        // 三个方法的执行顺序为：用手指拖动翻页时，最先执行一遍onPageScrollStateChanged（1），然后不断执行onPageScrolled，
        // 放手指的时候，直接立即执行一次onPageScrollStateChanged（2），
        // 然后立即执行一次onPageSelected，然后再不断执行onPageScrollStateChanged，最后执行一次onPageScrollStateChanged（0）。
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                for (TextView view : textViewList) {
                    view.setTextColor(Color.DKGRAY);
                }
                textViewList.get(position).setTextColor(Color.WHITE);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        // 检查有没有读取本地音乐权限，没有就请求获取
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_EXTERNAL_STORAGE);
        }

        // 初始化MainApp 设置播放列表
        initPlaylist();
    }

    @Override
    protected void onStart() {
        super.onStart();
        // 设置主页面当前正在播放音乐信息
        Music currentMusic = MainApp.getInstance().getCurrentMusic();
        if (currentMusic != null) {
            textView_name.setText(currentMusic.getName());
            textView_artist.setText(currentMusic.getArtist());
            imageView.setImageBitmap(currentMusic.getImgData());
        } else {
            textView_name.setText("未播放");
            textView_artist.setText("选择音乐播放");
            imageView.setImageResource(R.mipmap.image1);
        }
    }

    public void initPlaylist() {
        List<LocalMusic> musics = LocalMusicUtils.getmusic(this);
        ArrayList<Music> playlist = new ArrayList<>();
        int musicIndex = 0;
        for (LocalMusic localMusic : musics) {
            playlist.add(new Music(
                    musicIndex++,
                    localMusic.getName(),
                    LocalMusicUtils.getArtwork(this, localMusic.getId(), localMusic.getAlbumId(), true, true),
                    localMusic.getSinger(),
                    localMusic.getPath()
            ));
        }
        MainApp.getInstance().setPlaylist(playlist);
    }

    public void clickPlaylistButton(View view) {
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, PlaylistActivity.class);
                startActivity(intent);
            }
        });
    }

    public void clickBottomLayout(View view) {
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (MainApp.getInstance().getCurrentMusic() != null) {
                    Intent intent = new Intent(MainActivity.this, NowPlayingActivity.class);
                    intent.putExtra("current", MainApp.getInstance().getCurrentMusic().getId());
                    startActivity(intent);
                } else {
                    Toast.makeText(MainActivity.this, "当前没有正在播放的音乐！", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    public void addLocalMusicFragment(View view) {
        Toast.makeText(this, "正在获取本地音乐", Toast.LENGTH_SHORT).show();
        viewPager.setCurrentItem(0);
    }


    public void addOnlineMusicFragment(View view) {
        Toast.makeText(this, "正在获取在线音乐", Toast.LENGTH_SHORT).show();
        viewPager.setCurrentItem(1);
    }

    //更新按钮图标
    public void updatePlayImg() {
        if (musicBinder.isPlaying()) {
            playBtn.setImageResource(R.drawable.ic_play_btn_play);
        } else {
            playBtn.setImageResource(R.drawable.ic_play_btn_pause_pressed);
        }
    }

    //点击按钮播放/暂停音乐
    public void onPlayBtnClick(View view) {
        if(MainApp.getInstance().getCurrentMusic()!=null) {
            musicBinder.loadFile(MainApp.getInstance().getCurrentMusic().getFilepath());
            musicBinder.play();
            updatePlayImg();
        }else{
            Toast.makeText(this, "当前没有正在播放的音乐！", Toast.LENGTH_SHORT).show();
        }
    }

    //点击按钮下一首
    public void onNextBtnClick(View view) {
        musicBinder.reset();
        boolean result = MainApp.getInstance().next();
        if (!result) {
            Toast.makeText(this, "没有下一首可以播放了！", Toast.LENGTH_SHORT).show();
            return;
        }
        musicBinder.loadFile(MainApp.getInstance().getCurrentMusic().getFilepath());
        musicBinder.play();
    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_EXTERNAL_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 提示获取权限成功
                Toast.makeText(MainActivity.this, "获取本地音乐权限成功", Toast.LENGTH_LONG).show();
            } else {
                // 提示获取失败
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("警告")
                        .setMessage("您已经拒绝了获取本地音乐，请手动设置")
                        .setPositiveButton("去设置", null)
                        .setNegativeButton("不了", null)
                        .show();
            }
        }
    }
}
